package main

import "fmt"

// 实现一个通用的惰性生产器的工厂函数

type Any interface{}
type EvalFunc func(Any) (Any, Any)

func main() {
	evenFunc := func(state Any) (Any, Any) {
		os := state.(int)
		ns := os + 2
		return os, ns
	}

	even := BuildLazyIntEvaluator(evenFunc, 0)
	for i := 0; i < 6; i++ {
		fmt.Println(i, "- even:", even())
	}

}

func BuildLazyEvaluator(evalFunc EvalFunc, initState Any) func() Any {
	ch := make(chan Any)
	loopFunc := func() {
		var actState Any = initState
		var retState Any
		for {
			retState, actState = evalFunc(actState)
			ch <- retState
		}
	}
	go loopFunc()
	return func() Any {
		return <-ch
	}
}

func BuildLazyIntEvaluator(e EvalFunc, s Any) func() int {
	lazyIntEvaluator := BuildLazyEvaluator(e, s)
	return func() int {
		return lazyIntEvaluator().(int)
	}
}
